import {loginAPI, getLikeListAPI} from '@/api/user'
import {getUserOrder} from '@/api/order'
import {mergeCartAPI} from '@/api/cart'
import {setUserInfo, getUserInfo, removeUserInfo} from '@/utils/userinfo'
import store from '..'

const state = {
    // 登录后的用户信息
    userInfo: JSON.parse(getUserInfo()) || {},
    likeList: [],
    orderData: {},
}
const actions = {
    // 登录
    async login({commit}) {
        const user = JSON.parse(window.sessionStorage.getItem("user"))
        console.log(user)
        setUserInfo(JSON.stringify(user));
        commit('LOGINDATA', user)
        //     // 获取新购物车数据
        store.dispatch('cartstore/getNewCartList')
    },
    // 退出登录清除用户存储信息
    clearUserInfo({commit}) {
        // 清除本地存储的用户数据
        removeUserInfo();
        // 清除仓库中的用户数据
        commit('CLEARUSERINFO');
        // 执行清除购物车的action
        store.dispatch('cartstore/clearCart');
    },
    // 获取猜你喜欢的数据
    async getLikeList({commit}, data) {
        let res = await getLikeListAPI(data);
        if (res.code == 1) {
            commit('GETLIKELIST', res.result);
        }
    },
    // 获取我的订单列表的数据
    async getOrderList({commit}, data) {
        let res = await getUserOrder(data);
        console.log(res)
        if (res.status) {
            commit('GETORDERLIST', res.data);
        }
    }

}
const mutations = {
    LOGINDATA(state, userInfo) {
        state.userInfo = userInfo;
    },
    CLEARUSERINFO(state) {
        state.userInfo = {};
    },
    GETLIKELIST(state, likeList) {
        state.likeList = likeList;
    },
    GETORDERLIST(state, orderData) {
        state.orderData = orderData;
    }
}
const getters = {
    orderList(state) {
        return state.orderData || [];
    },
    counts(state) {
        return state.orderData.counts || 0;
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters,
}
